﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;

namespace Tcp服务器端
{
    class Program
    {
        //处理到了  13
        static void Main(string[] args)
        {
            StartServerAsync();
            Console.ReadKey();
        }

        /// <summary>
        /// 异步
        /// </summary>
        static void StartServerAsync()
        {
            Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //本机ip : 192.168.1.4(局域网ip)    127.0.0.1
            //IPAddress ipAdress = new IPAddress(new byte[] { 192, 168, 1, 4 });
            IPAddress ipAress = IPAddress.Parse("192.168.1.4");
            IPEndPoint ipEndPoint = new IPEndPoint(ipAress, 88);
            serverSocket.Bind(ipEndPoint);//绑定ip和port（端口号）
            serverSocket.Listen(10);//处理链接的对列数量 0 不限

            //Socket clientSocket = serverSocket.Accept();//接受一个客户端连接
            serverSocket.BeginAccept(AcccptCallBack, serverSocket);
        }

        static Message msg = new Message();

        static void AcccptCallBack(IAsyncResult ar)
        {
            Socket serverSocket = ar.AsyncState as Socket;
            Socket clientSocket = serverSocket.EndAccept(ar);

            //向客户端发送一个消息
            string msgStr = "Hello client ! 你好...";
            byte[] data = Encoding.UTF8.GetBytes(msgStr);
            clientSocket.Send(data);

            //开始监听客户端信息,接收数据
            clientSocket.BeginReceive(msg.Data, msg.StartIndex, msg.ReaminSize, SocketFlags.None, ReceiveCallBack, clientSocket);

            //接着处理下一条数据
            serverSocket.BeginAccept(AcccptCallBack, serverSocket);
        }

        static byte[] dataBuffer = new byte[1024];
        static void ReceiveCallBack(IAsyncResult ar)
        {
            Socket clientSocket = null;
            //try catch用来处理非正常关闭
            try
            {
                clientSocket = ar.AsyncState as Socket;
                //异步结束接受消息
                int count = clientSocket.EndReceive(ar);
                if (count == 0)
                {
                    //空数据，关闭
                    clientSocket.Close();
                    return;
                }
                msg.AddCount(count);
                //string msgStr = Encoding.UTF8.GetString(dataBuffer, 0, count);
                //Console.WriteLine("从客户端接收到数据：" + msgStr);
                msg.ReadMessage();
                //异步开始接收客户端数据
                //clientSocket.BeginReceive(dataBuffer, 0, 1024, SocketFlags.None, ReceiveCallBack, clientSocket);

                clientSocket.BeginReceive(msg.Data, msg.StartIndex, msg.ReaminSize, SocketFlags.None, ReceiveCallBack, clientSocket);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                if (clientSocket != null)
                    clientSocket.Close();
            }
            finally
            {
                
            }
        }

        /// <summary>
        /// 同步
        /// </summary>
        void StartServerSync()
        {
            Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //本机ip : 192.168.1.4(局域网ip)    127.0.0.1
            //IPAddress ipAdress = new IPAddress(new byte[] { 192, 168, 1, 4 });
            IPAddress ipAress = IPAddress.Parse("192.168.1.4");
            IPEndPoint ipEndPoint = new IPEndPoint(ipAress, 88);
            serverSocket.Bind(ipEndPoint);//绑定ip和port（端口号）
            serverSocket.Listen(10);//处理链接的对列数量 0 不限

            Socket clientSocket = serverSocket.Accept();//接受一个客户端连接

            //向客户端发送一个消息
            string msgStr = "Hello client ! 你好...";
            byte[] data = Encoding.UTF8.GetBytes(msgStr);
            clientSocket.Send(data);

            //接受客户端的一条数据
            byte[] dataBuffer = new byte[1024];
            int count = clientSocket.Receive(dataBuffer);//接受到数据的长度
            string msgReceive = Encoding.UTF8.GetString(dataBuffer, 0,count);
            Console.WriteLine(msgReceive);

            Console.ReadKey();
            //关闭跟客户端的链接
            clientSocket.Close();
            serverSocket.Close();
        }
    }
}
